package com.servlet;

import com.dao.TypeDAO;
import com.dao.impl.TypeDAOImpl;
import com.entity.Type;
import com.google.gson.Gson;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.List;

/**
 * 商品类型查询 Servlet
 *
 * @author XCH
 * @date 2024-11-27
 */
@WebServlet("/type")
public class TypeServlet extends HttpServlet {
    private final TypeDAO typeDAO = new TypeDAOImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json; charset=UTF-8");
        String action = request.getParameter("action");
        Gson gson = new Gson();

        if ("list".equals(action)) {
            List<Type> types = typeDAO.getAllType();
            if (types != null && !types.isEmpty()) {
                response.getWriter().print(gson.toJson(types));
            } else {
                // 返回空数组，确保是有效的 JSON 格式
                response.getWriter().print("[]");
            }
        } else if ("get".equals(action)) {
            int id = Integer.parseInt(request.getParameter("id"));
            String name = typeDAO.getTypeNameById(id);
            response.getWriter().print(gson.toJson(new Type(id, name)));
        } else {
            response.getWriter().print("[]");  // 返回空数组
        }
    }

}
